package util;
import java.io.*;
public class QuebraTexto {


	RandomAccessFile raf;
	String file;
	int qntDeArquivosParaQuebrar = 100; //mudar dinamicamente



	public QuebraTexto(String file){
		try{
			this.file = file;
			File f = new File(file);
			raf = new RandomAccessFile(f, "r");
			long length = this.count();
			
			for (long i = 0; i < length; i=(i+length/qntDeArquivosParaQuebrar)) {
				stripString(i, i+length/qntDeArquivosParaQuebrar, "temp"+i/(length/qntDeArquivosParaQuebrar)+".txt");
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}




	/*
	 * Quebra o arquivo com a posicao desejada
	 */
	//TODO verificar uma forma mais rapida de escrever no arquivo usando buffer (Substituir Random Access File)


	private void stripString(long initPos, long endPos, String fileName) throws IOException{		
		//10 segundos
		File temp = new File(fileName);
		RandomAccessFile raf = new RandomAccessFile(temp, "rw");

		//1 segundo
		FileWriter fstream = new FileWriter(fileName);
		BufferedWriter out = new BufferedWriter(fstream);

		Boolean record = false;
		InputStream is = new BufferedInputStream(new FileInputStream(file));
		try {
			byte[] c = new byte[1024];
			int count = 0;
			int readChars = 0;
			while ((readChars = is.read(c)) != -1) {
				for (int i = 0; i < readChars; ++i) {
					if (record){
						//out.write(c[i]);
						raf.write(c[i]);
					}
					if (c[i] == '\n'){
						++count;
						if ((count >= initPos) && count <= endPos){
							record = true;
						}else
							record = false;
					}
				}
			}
		} finally {
			is.close();
			out.close();
		}
	}

	private int count() throws IOException {
		InputStream is = new BufferedInputStream(new FileInputStream(file));
		//DataInputStream d = new DataInputStream(is);
		//trabalhar em bytes
		try {
			byte[] c = new byte[1024];
			int count = 0;
			int readChars = 0;
			while ((readChars = is.read(c)) != -1) {
				for (int i = 0; i < readChars; ++i) {
					if (c[i] == '\n')
						++count;
				}
			}
			return count;
		} finally {
			is.close();
		}
	}



}
